package com.miao.util.basic;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by miao on 2015/4/16.
 */
public class ExcutorUtil {
    private static ExcutorUtil util;
    private static ExecutorService executorService;

    private ExcutorUtil() {
        int fix = Runtime.getRuntime().availableProcessors();
        System.out.println("fix=" + fix);
        executorService = Executors.newFixedThreadPool(fix);
    }

    public static synchronized ExcutorUtil getSingleInstance() {
        if (util == null) {
            util = new ExcutorUtil();
        }
        return util;
    }

    public static void main(String[] args) throws InterruptedException {
        int index = 1;
        for (int i = 0; i < 20; i++) {
            System.out.println(index++);
            test(index);
            Thread.sleep(1000L);
        }
        System.out.println("-----------------------");
    }

    public static void test(final int index) {
        ExcutorUtil service = getSingleInstance();
        service.execute(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000L);
                    System.out.println(" Thread :" + index);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public synchronized void execute(Runnable task) {
        executorService.execute(task);
    }

    public synchronized Future<?> submit(Callable<?> task) {
        Future f = executorService.submit(task);
        return f;
    }

    public void shutdown() {
        executorService.shutdown();
    }
}
